package com.test.demoapp.ui.his

import android.os.Bundle
import android.os.Handler
import android.view.View
import com.test.demoapp.R
import com.test.demoapp.adapter.HisAdapter
import com.test.demoapp.base.BaseFragment
import com.test.demoapp.entity.NewEvent
import com.test.demoapp.entity.RespVo
import com.test.demoapp.http.BaseURLConfig
import com.test.demoapp.util.getSpListValue
import kotlinx.android.synthetic.main.fragment_query.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.ArrayList

class HisFragment : BaseFragment() {
    private var mAdapter: HisAdapter? = null

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        EventBus.getDefault().register(this)
    }

    override fun init() {
        mAdapter = HisAdapter()
        rv_area.adapter = mAdapter
        rv_area.itemAnimator = null

        srl_area.setOnRefreshListener {
            Handler().postDelayed({
                getHisData()
            }, 1000)

        }
        getHisData()
    }

    override fun onResume() {
        super.onResume()
        getHisData()
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden) {
            getHisData()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun hasNewData(event: NewEvent) {
        tv_new.visibility = View.VISIBLE
    }

    private fun getHisData() {
        var his =
            getSpListValue(key = BaseURLConfig.KEY_HIS_DATA, cls = RespVo::class.java) as ArrayList
        his.reverse()
        mAdapter?.setNewData(his)
        srl_area.isRefreshing = false
        tv_new.visibility = View.GONE
    }

    override fun setLayoutId(): Int {
        return R.layout.fragment_query
    }

    override fun onDestroyView() {
        super.onDestroyView()
        EventBus.getDefault().unregister(this)
    }
}
